package com.ld.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.ld.explanation.TextExplanation;
import org.jetbrains.annotations.NotNull;

public class Translate extends AnAction {

    public Translate(){

    }
    @Override
    public void update(@NotNull AnActionEvent e) {
        super.update(e);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext());
        if (editor != null){
            String selectedText = editor.getSelectionModel().getSelectedText();
            int selectionStart = editor.getSelectionModel().getSelectionStart();
            int selectionEnd = editor.getSelectionModel().getSelectionEnd();
            if (selectedText != null && selectedText != ""){
                String translation = TextExplanation.getTextExplanation(editor).translation();
                WriteCommandAction.runWriteCommandAction(editor.getProject(),()->{
                    editor.getDocument().replaceString(selectionStart,selectionEnd,translation);
                });
            }
        }
    }
}